package com.thf.interceptor;


import com.thf.exception.InterceptorException;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginInterceptor implements HandlerInterceptor {
    /**
     * 请求在控制器到达之前先行执行的方法
     * @param httpServletRequest
     * @param httpServletResponse
     * @param o
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws InterceptorException {
//        String username = (String) httpServletRequest.getSession().getAttribute("username");
//        if(username == null){
//            throw new InterceptorException();
//        }
        String authorization = httpServletRequest.getHeader("Authorization");
        String token = StringUtils.substring(authorization, "bearer".length()).trim();
        if(token == null || token.length() <= 0){
            throw new InterceptorException();
        }
        Claims claims = Jwts.parser()
                .setSigningKey("mySecret")
                .parseClaimsJws(token)
                .getBody();
        String username = (String) claims.get("username");
        if(username == null || username.length() <= 0){
            throw new InterceptorException();
        }
        return true;
    }

    /**
     * 请求到达控制器之后执行的方法
     * @param httpServletRequest
     * @param httpServletResponse
     * @param o
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    /**
     * 页面加载完成后执行的方法
     * @param httpServletRequest
     * @param httpServletResponse
     * @param o
     * @param e
     * @throws Exception
     */
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
